﻿using System;
using System.Collections.Generic;
using System.Linq;
using SecurityLog.Models;

namespace SecurityLog.Repositories
{
    public class LogRepository : ILogRepository
    {
        private ModelDataContext _ctx;

        public LogRepository()
        {
            _ctx = new ModelDataContext();
        }

        public LogRepository(ModelDataContext ctx)
        {
            _ctx = ctx;
        }

        public IEnumerable<SingleEntryViewModel> GetCurrentLog(DateTime time)
        {

             return (from entry in _ctx.Entries
                    join cat in _ctx.Categories
                    on entry.CategoryId equals cat.Id
                    join users in _ctx.Users
                    on entry.UserId equals users.Id
                    where entry.Created > time
                    orderby entry.Created descending
              select new SingleEntryViewModel
              {
                  ID = entry.Id,
                  userName = users.Name,
                  body = entry.Body,
                  category = cat.Name,
                  dateCreated = entry.Created});

        }


        public void InsertEntry(Entry entry)
        {
            _ctx.Entries.InsertOnSubmit(entry);
        }

        public void SaveChanges()
        {
            _ctx.SubmitChanges();
        }

        public IEnumerable<Category> GetCategoryList()
        {
            return (from cat in _ctx.Categories
                    orderby cat.Name
                    select cat);
        }
    }
}